<template>
</template>

<script>
export default {
  name: "WebSocket",
  data() {
    return {
      socketHost: 'ws://127.0.0.1:19000',
      // 回调函数对象
      awaitingPromises: [],
      // 每发送一条消息，自加1,对应回调函数对象的seq属性
      promiseSeq: 0
    }
  },
  created() {
    this.connectionSocket();
  },
  destroyed() {
    this.webSocket.close();
  },
  methods: {
    // 连接到Socket
    connectionSocket: function () {
      this.webSocket = new WebSocket(this.socketHost);
      this.webSocket.onopen = this.onOpen;
      this.webSocket.onmessage = this.onMessage;
      this.webSocket.onclose = this.onClose;
      this.webSocket.onerror = this.onError;
    },
    onOpen: function (evt) {
      console.log('连接打开');
    },
    onMessage: function (evt) {
      console.log('接收到消息', evt.data);
      const res = JSON.parse(evt.data);
      if (res.seq in this.awaitingPromises) {
        // 按回调函数管理对象seq属性触发回调函数
        this.awaitingPromises[res.seq].callback({code: res.code, errMsg: '', data: res.data});
        delete this.awaitingPromises[res.seq];
      }
    },
    onClose: function (evt) {
      console.log(evt);
      console.log('连接关闭');
      this.webSocket = new WebSocket(this.socketHost);
    },
    onError: function (evt) {
      console.log(evt);
      console.log('连接错误');
      this.webSocket = new WebSocket(this.socketHost);
    },
    sendMsg: function (cmd, msg, callback) {
      const sendData = {
        seq: ++this.promiseSeq,
        cmd: cmd,
        timestamp: new Date().valueOf(),
        data: msg
      };
      // 发送消息后添加到回调函数管理对象
      if (typeof callback === 'function') {
        this.awaitingPromises[this.promiseSeq] = {callback: callback};
      }
      this.webSocket.send(JSON.stringify(sendData));
    }
  }
}
</script>

<style scoped>

</style>